package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"os"
	"path/filepath"

	"mcp-server/internal/docprocessor"
	"mcp-server/internal/types"
)

func main() {
	// 定义命令行参数
	var (
		inputPath    = flag.String("input", "", "输入文件或目录路径")
		outputPath   = flag.String("output", "", "输出文件路径（JSON格式）")
		recursive    = flag.Bool("recursive", false, "递归处理子目录")
		verbose      = flag.Bool("verbose", false, "详细输出")
		maxChunkSize = flag.Int("max-chunk-size", 1000, "最大分片大小（字符数）")
		minChunkSize = flag.Int("min-chunk-size", 100, "最小分片大小（字符数）")
		overlapSize  = flag.Int("overlap-size", 50, "重叠大小（字符数）")
		semantic     = flag.Bool("semantic", true, "启用语义分析")
	)

	flag.Parse()

	// 检查必需参数
	if *inputPath == "" {
		fmt.Println("错误: 必须指定输入路径")
		flag.Usage()
		os.Exit(1)
	}

	// 创建分片配置
	config := &types.SplitConfig{
		MaxChunkSize:      *maxChunkSize,
		MinChunkSize:      *minChunkSize,
		OverlapSize:       *overlapSize,
		EnableSemantic:    *semantic,
		PreserveParagraph: true,
		RemoveEmptyLines:  true,
		SemanticTags:      []string{"定义", "示例", "操作步骤", "注意事项", "说明", "规定", "条款", "附则"},
	}

	// 创建文档处理器
	processor := docprocessor.NewDocumentProcessor()
	processor.SetConfig(config)

	// 验证配置
	if err := processor.ValidateConfig(config); err != nil {
		fmt.Printf("配置错误: %v\n", err)
		os.Exit(1)
	}

	// 检查输入路径
	fileInfo, err := os.Stat(*inputPath)
	if err != nil {
		fmt.Printf("输入路径错误: %v\n", err)
		os.Exit(1)
	}

	var results []*types.SplitResult

	if fileInfo.IsDir() {
		// 处理目录
		if *verbose {
			fmt.Printf("处理目录: %s\n", *inputPath)
		}
		results, err = processor.ProcessDirectory(*inputPath, *recursive)
		if err != nil {
			fmt.Printf("处理目录失败: %v\n", err)
			os.Exit(1)
		}
	} else {
		// 处理单个文件
		if *verbose {
			fmt.Printf("处理文件: %s\n", *inputPath)
		}
		result, err := processor.ProcessFile(*inputPath)
		if err != nil {
			fmt.Printf("处理文件失败: %v\n", err)
			os.Exit(1)
		}
		results = []*types.SplitResult{result}
	}

	// 输出结果
	if *verbose {
		printVerboseResults(results, processor)
	}

	// 保存结果到文件
	if *outputPath != "" {
		if err := saveResults(results, *outputPath); err != nil {
			fmt.Printf("保存结果失败: %v\n", err)
			os.Exit(1)
		}
		fmt.Printf("结果已保存到: %s\n", *outputPath)
	}

	// 输出统计信息
	stats := processor.GetStatistics(results)
	fmt.Println("\n=== 处理统计 ===")
	fmt.Printf("总文件数: %d\n", stats["total_files"])
	fmt.Printf("成功处理: %d\n", stats["success_count"])
	fmt.Printf("处理失败: %d\n", stats["failure_count"])
	fmt.Printf("总分片数: %d\n", stats["total_chunks"])
	fmt.Printf("平均分片数/文件: %.2f\n", stats["average_chunks_per_file"])
	fmt.Printf("总处理时间: %d ms\n", stats["total_process_time_ms"])
	if avgTime, ok := stats["average_process_time_ms"]; ok {
		fmt.Printf("平均处理时间: %.2f ms\n", avgTime)
	}
}

// printVerboseResults 打印详细结果
func printVerboseResults(results []*types.SplitResult, processor *docprocessor.DocumentProcessor) {
	fmt.Println("\n=== 处理结果 ===")

	for i, result := range results {
		fmt.Printf("\n文件 %d:\n", i+1)
		if result.Document != nil {
			fmt.Printf("  路径: %s\n", result.Document.FilePath)
			fmt.Printf("  大小: %d bytes\n", result.Document.FileSize)
			fmt.Printf("  行数: %d\n", result.Document.TotalLines)
			fmt.Printf("  分片数: %d\n", result.Document.TotalChunks)
			fmt.Printf("  处理时间: %d ms\n", result.Document.ProcessTime)
		}

		if !result.Success {
			fmt.Printf("  错误: %s\n", result.Error)
			continue
		}

		fmt.Printf("  分片详情:\n")
		for j, chunk := range result.Chunks {
			fmt.Printf("    分片 %d: ID=%s, 行数=%d-%d, 大小=%d字符",
				j+1, chunk.ID, chunk.StartLine, chunk.EndLine, len([]rune(chunk.Content)))
			if chunk.SemanticTag != "" {
				fmt.Printf(", 语义标签=%s", chunk.SemanticTag)
			}
			fmt.Println()

			// 显示分片内容预览（前100字符）
			preview := chunk.Content
			if len([]rune(preview)) > 100 {
				preview = string([]rune(preview)[:100]) + "..."
			}
			fmt.Printf("      内容预览: %s\n", preview)
		}
	}
}

// saveResults 保存结果到JSON文件
func saveResults(results []*types.SplitResult, outputPath string) error {
	// 确保输出目录存在
	outputDir := filepath.Dir(outputPath)
	if err := os.MkdirAll(outputDir, 0755); err != nil {
		return fmt.Errorf("创建输出目录失败: %v", err)
	}

	// 序列化结果
	data, err := json.MarshalIndent(results, "", "  ")
	if err != nil {
		return fmt.Errorf("序列化结果失败: %v", err)
	}

	// 写入文件
	if err := os.WriteFile(outputPath, data, 0644); err != nil {
		return fmt.Errorf("写入文件失败: %v", err)
	}

	return nil
}
